package utils

import (
	"fmt"
	"gin-luban-server/global"
	"github.com/xanzy/go-gitlab"
	"go.uber.org/zap"
	"net/url"
	"strconv"
	"strings"
	"time"
)

type GitlabClient struct {
	User                string
	Password            string
	UrlRepo             string
}

type GitlabBranchNameList struct {
	BranchName          string
}

type GitlabTag struct {
	TagName             string `json:"tag_name"`
	TagMessage			string `json:"tag_message"`
	TagCommitID			string	`json:"tag_commit_id"`
	TagCommitMessage	string `json:"tag_commit_message"`  // tag对应的commit提交
}


// 指定APP仓库Repo的信息
type GitLabRepoInfo struct {
	BranchList []string `json:"branch_list""`
	TagList []GitlabTag	`json:"tag_list"`
}

////名称和路径的接口
//func GetGitlabByPathWithNamespace(params  *GitlabClient) (data string,err error ) {
//	urlStr, err := url.Parse(params.UrlRepo)
//	baseURl := ""
//	var NameSpace string
//	if !strings.HasPrefix(urlStr.Host, "http://") && !strings.HasPrefix(urlStr.Host, "https://") {
//		baseURl = "http://" + urlStr.Host
//	}
//	groupName :=strings.Split(urlStr.Path, "/")
//	git, err := gitlab.NewBasicAuthClient(
//		params.User,
//		params.Password,
//		gitlab.WithBaseURL(baseURl),
//	)
//	if err != nil {
//		LogError(err)
//	}
//	opt := &gitlab.ListProjectsOptions{Search: gitlab.String(groupName[1])}
//	projects, _, err := git.Projects.ListProjects(opt)
//	if err != nil {
//		LogError(err)
//	}
//	for _,p := range projects {
//		if p.HTTPURLToRepo == params.UrlRepo {
//			NameSpace = p.PathWithNamespace
//			break
//		}
//	}
//	PathWithNamespace := strings.Split(NameSpace, "=")
//	data = PathWithNamespace[0]
//	return data,err
//
//}
//取分支的接口
func GetDeployAppBranchList(params  *GitlabClient) ([]GitlabBranchNameList,error ) {
	urlStr, err := url.Parse(params.UrlRepo)
	baseURl := ""
	var (
		ID         int
		branchName string
	)
	var dataList []GitlabBranchNameList
	if !strings.HasPrefix(urlStr.Host, "http://") && !strings.HasPrefix(urlStr.Host, "https://") {
		baseURl = "http://" + urlStr.Host
	}
	groupName :=strings.Split(urlStr.Path, "/")
	git, err := gitlab.NewBasicAuthClient(
		params.User,
		params.Password,
		gitlab.WithBaseURL(baseURl),
	)
	if err != nil {
		global.GVA_LOG.Error("gitlab连接报错！", zap.Any("err", err))
	}
	opt := &gitlab.ListProjectsOptions{Search: gitlab.String(groupName[1])}
	projects, _, err := git.Projects.ListProjects(opt)
	if err != nil {
		global.GVA_LOG.Error("gitlab查询项目报错！", zap.Any("err", err))
	}
	for _,p := range projects {
		if p.HTTPURLToRepo == params.UrlRepo {
			ID = p.ID
			break
		}
	}
	pid :=strconv.Itoa(ID)
	opts := new(gitlab.ListBranchesOptions)
	opts.Page = 1
	opts.PerPage = 100
	branch,_,err :=git.Branches.ListBranches(pid,opts)
	for _,b := range branch {
		branchName = b.Name
		BranchName := strings.Split(branchName,"=")
		gitBranchName := BranchName[0]
		dataList = append(dataList,GitlabBranchNameList{
			BranchName:gitBranchName,
		})
	}
	return dataList,err
}


//获取仓库下的 分支、tag信息列表
func GetAppGitRepoInfo(params  *GitlabClient) (dataList GitLabRepoInfo, err error ) {
	urlStr, err := url.Parse(params.UrlRepo)
	baseURl := ""
	var (
		ID         int
		tagsName string
	)
	if !strings.HasPrefix(urlStr.Host, "http://") && !strings.HasPrefix(urlStr.Host, "https://") {
		baseURl = "http://" + urlStr.Host
	}

	start := time.Now()   // 计算时间
	groupName :=strings.Split(urlStr.Path, "/")
	fmt.Println(groupName)
	git, err := gitlab.NewBasicAuthClient(
		params.User,
		params.Password,
		gitlab.WithBaseURL(baseURl),
	)
	if err != nil {
		global.GVA_LOG.Error("gitlab连接报错！", zap.Any("err", err))
	}
	// 测试此接口耗时大概400ms
	opt := &gitlab.ListProjectsOptions{Search: gitlab.String(groupName[len(groupName) -2]), ListOptions: gitlab.ListOptions{Page: 1, PerPage: 100} }

	projects, _, err := git.Projects.ListProjects(opt)
	if err != nil {
		global.GVA_LOG.Error("gitlab查询项目报错！", zap.Any("err", err))
	}
	cost := time.Since(start)  // 消耗时间
	fmt.Printf("git lab接口耗时: cost=[%s]\n",cost)
	for _,p := range projects {
		//fmt.Println(p.HTTPURLToRepo, "-----------")
		if p.HTTPURLToRepo == params.UrlRepo {
			ID = p.ID
			break
		}
	}
	pid :=strconv.Itoa(ID)
	// 获取tag列表
	tagOpts := new(gitlab.ListTagsOptions)
	tagOpts.Page = 1
	tagOpts.PerPage = 100
	tags,_,err :=git.Tags.ListTags(pid,tagOpts)
	for _,b := range tags {
		tempTag := GitlabTag{
			TagName: strings.Split(b.Name, "=")[0],
			TagMessage: b.Message,
			TagCommitID: b.Commit.ID,
			TagCommitMessage: b.Commit.Message,
		}
		dataList.TagList = append(dataList.TagList,tempTag)
	}

	// 获取分支列表
	branchOpts := new(gitlab.ListBranchesOptions)
	branchOpts.Page = 1
	branchOpts.PerPage = 100
	branches,_,err :=git.Branches.ListBranches(pid,branchOpts)
	for _,b := range branches {
		tagsName = b.Name
		TagsName := strings.Split(tagsName,"=")
		gitTagsName := TagsName[0]
		dataList.BranchList = append(dataList.BranchList,gitTagsName)

	}
	return dataList,err
}










